#import "CTKeyboardInputView.h"
#import "UITextView+Extension.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
@interface CTKeyboardInputView () <UITextViewDelegate>
{
    NSUInteger currentCount;
    CGFloat keyBoardHeight;
    NSString * _defaultContent;
    NSInteger contentChangedNum;
}
@property (nonatomic,strong) UIVisualEffectView *backgroundView;
@property (nonatomic,strong) UIView *shadowView;
@property (nonatomic,strong) UIView *keyBoardView;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) UILabel *countLabel;
@property (nonatomic,strong) UIButton *closeButton;
@property (nonatomic,strong) UIButton *doneButton;
@end
@implementation CTKeyboardInputView
- (instancetype)init
{
    if (self = [super init]) {
        currentCount = 0;
        [self setupSubViews];
    }
    return self;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}
- (void)setupSubViews
{
    self.frame = [UIScreen mainScreen].bounds;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.backgroundView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    self.backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.backgroundView.frame = self.bounds;
    [self addSubview:self.backgroundView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [self.backgroundView addGestureRecognizer:tap];
    self.shadowView.frame = CGRectMake(0, screenSize.height - 247, screenSize.width, 247);
    [self addSubview:self.shadowView];
    self.keyBoardView = [UIView new];
    self.keyBoardView.backgroundColor = [UIColor whiteColor];
    self.keyBoardView.frame = self.shadowView.bounds;
    [self.shadowView addSubview:self.keyBoardView];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.keyBoardView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(13,13)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.keyBoardView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.keyBoardView.layer.mask = maskLayer;
    [self.keyBoardView addSubview:self.titleLabel];
    [self.keyBoardView addSubview:self.textView];
    self.textView.delegate = self;
    [self.keyBoardView addSubview:self.closeButton];
    [self.keyBoardView addSubview:self.doneButton];
    [self.keyBoardView addSubview:self.countLabel];
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0];
    [self.keyBoardView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(SINGLE_LINE_WIDTH);
        make.bottom.mas_equalTo(self.doneButton.mas_top).offset(-20);
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(20);
    }];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleLabel);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(30);
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(self.countLabel.mas_top).offset(-6);
    }];
    [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(40);
        make.top.mas_equalTo(6.5);
        make.right.mas_equalTo(-6.5);
    }];
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(-15);
        make.height.mas_equalTo(45);
    }];
    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(lineView.mas_top).offset(-20);
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden:) name:UIKeyboardWillHideNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChangedExt:) name:UITextViewTextDidChangeNotification object:self.textView];
}
#pragma mark - Getter
- (UIView *)shadowView
{
    if(!_shadowView) {
        _shadowView = [[UIView alloc] init];
        _shadowView.layer.masksToBounds = NO;
        _shadowView.layer.shadowOffset = CGSizeMake(0, 0);
        _shadowView.layer.shadowRadius = 23;
        _shadowView.layer.shadowOpacity = 1;
        _shadowView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1].CGColor;
    }
    return _shadowView;
}
- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.font = [UIFont boldSystemFontOfSize:18.f];
        _titleLabel.textColor = [UIColor blackColor];
    }
    return _titleLabel;
}
- (UILabel *)countLabel
{
    if (!_countLabel) {
        _countLabel = [UILabel new];
        _countLabel.font = [UIFont systemFontOfSize:13.f];
        _countLabel.textColor = [UIColor colorWithRed:48/255.0 green:114/255.0 blue:246/255.0 alpha:1.0];
    }
    return _countLabel;
}
- (UITextView *)textView
{
    if (!_textView) {
        _textView = [[UITextView alloc] init];
        _textView.delegate = self;
        _textView.font = [UIFont systemFontOfSize:14.f];
        _textView.textColor = [UIColor blackColor];
    }
    return _textView;
}
- (UIButton *)closeButton
{
    if (!_closeButton) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
        [_closeButton setImage:[UIImage imageNamed:@"input_close"] forState:UIControlStateNormal];
    }
    return _closeButton;
}
- (UIButton *)doneButton
{
    if (!_doneButton) {
        _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneButton addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
        _doneButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [_doneButton setTitle:@"Complete" forState:UIControlStateNormal];
        [_doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _doneButton.backgroundColor = [UIColor colorFF6C2E];
        _doneButton.layer.shadowColor = [UIColor colorWithRed:48/255.0 green:114/255.0 blue:246/255.0 alpha:0.3].CGColor;
        _doneButton.layer.shadowOffset = CGSizeMake(0,5);
        _doneButton.layer.shadowOpacity = 1;
        _doneButton.layer.shadowRadius = 9;
        _doneButton.layer.cornerRadius = 5.0;
    }
    return _doneButton;
}
#pragma mark - private
- (NSString *)textCountWithCurrentCount:(NSUInteger)aCurrentCount total:(NSUInteger)aTotalCount
{
    if (aTotalCount == 0) {
        return @"";
    }
    if (aCurrentCount >= aTotalCount ) {
        NSString *tep = self.textView.text;
        self.countLabel.textColor = [UIColor redColor];
    }
    else
    {
        self.countLabel.textColor = [UIColor color888];
    }
    return [NSString stringWithFormat:@"%ld/%ld",aCurrentCount,aTotalCount];
}
- (UIImage *)snapshotScreenInView:(UIView *)contentView {
    CGSize size = contentView.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect rect = contentView.frame;
    [contentView drawViewHierarchyInRect:rect afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - Set
- (void)setTitle:(NSString *)title
{
    _title = title;
    _titleLabel.text = title;
}
- (void)setContentPlaceHolder:(NSString *)contentPlaceHolder
{
    _contentPlaceHolder = contentPlaceHolder;
    UIColor * placeColor = [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1.0];
    [self.textView was_setPlaceholderWithText:contentPlaceHolder Color:placeColor];
}
- (void)setMaxInputLength:(NSInteger)maxInputLength
{
    _maxInputLength = maxInputLength;
    self.countLabel.text = [self textCountWithCurrentCount:currentCount total:maxInputLength];
}
- (void)setContentText:(NSString *)contentText
{
    _contentText = contentText;
    if (contentChangedNum == 0) {
        _defaultContent = contentText;
    }
    if (contentText.length) {
        _textView.text = contentText;
        currentCount = [self.textView.text length];
        _countLabel.text = [self textCountWithCurrentCount:currentCount total:self.maxInputLength];
    }
}
- (void)setDoneTitle:(NSString *)doneTitle {
    _doneTitle = doneTitle;
    [_doneButton setTitle:doneTitle forState:UIControlStateNormal];
    [_doneButton setTitle:doneTitle forState:UIControlStateSelected];
}
#pragma mark - Anim
- (void)show
{
    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    [rootWindow addSubview:self];
    [self.textView becomeFirstResponder];
    self.backgroundView.alpha = 0;
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        self.backgroundView.alpha = 1;
    } completion:^(BOOL finished) {
    }];
}
- (void)dismiss
{
    [self endEditing:YES];
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
- (void)sendAction:(id)sender
{
    NSString *value = self.textView.text;
    if ([_defaultContent isEqualToString:value]) {
        [self endEditing:YES];
        [self dismiss];
        return;
    }
    [self endEditing:YES];
    [self dismiss];
    if (self.inputTextEndBlock) {
        self.inputTextEndBlock(value);
    }
}
- (void)closeAction:(id)sender
{
    [self dismiss];
}
#pragma mark - UIKeyboard
- (void)keyboardDidShow:(NSNotification *)notification{
    CGRect keyBoardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat deltaY = keyBoardRect.size.height;
    keyBoardHeight = deltaY;
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        self.shadowView.transform = CGAffineTransformMakeTranslation(0, -deltaY);
    }];
}
- (void)keyboardDidHidden:(NSNotification *)notification{
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        self.shadowView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
    }];
}
- (void)textChangedExt:(NSNotification *)notification {
    NSInteger number = [self.textView.text length];
    NSString *str = [self textCountWithCurrentCount:number total:self.maxInputLength];
    self.countLabel.text = str;
}
#pragma mark - UITextViewDelegate
#pragma mark - lazyLoading
- (UIVisualEffectView *)backgroundView {
    if (!_backgroundView) {
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _backgroundView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        _backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _backgroundView.frame = self.bounds;
        _backgroundView.userInteractionEnabled = YES;
    }
    return _backgroundView;
}
@end
